class EventsController < ApplicationController

  before_filter :require_admin, :except => [:show, :volunteer]

  # GET /events
  # GET /events.xml

  def volunteer
    @event = Event.find(params[:event_id])
    if !current_user.person.is_a_volunteer_for(@event)
      current_user.person.volunteer(@event)
    else
      flash[:notice] = "You have already volunteered for #{@event.name}"
      redirect_to dashboard_path(current_user) and return
    end
    if current_user.save
      flash[:notice] = "You have successfully volunteered for #{@event.name}"
      redirect_to dashboard_path(current_user) and return
    else
      raise "a problem has occured"
    end
  end

  def index
    @events = Event.find(:all, :order => "ends_at DESC")

    if request.xhr?
      render :layout => false
    end
  end

  # GET /events/1
  # GET /events/1.xml
  def show
    @event = Event.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @event }
    end
  end

  # GET /events/new
  # GET /events/new.xml
  def new
    @event = Event.new

    if request.xhr?
      render :layout => false
    end
  end

  # GET /events/1/edit
  def edit
    @event = Event.find(params[:id])
  end

  # POST /events
  # POST /events.xml
  def create
    @event = Event.new(params[:event])

    if @event.save
      flash[:notice] = "Event #{@event.name} was successfully created."
      redirect_to(events_path)
    else
      render :action => "new"
    end
  end

  # PUT /events/1
  # PUT /events/1.xml
  def update
    @event = Event.find(params[:id])

    if @event.update_attributes(params[:event])
      flash[:notice] = "Event #{@event.name} was successfully updated."
      redirect_to(events_path)
    else
      render :action => "edit"
    end

  end

  # DELETE /events/1
  # DELETE /events/1.xml
  def destroy

    flash[:notice] = "Event #{@event.name} removed."
    @event = Event.find(params[:id])
    @event.destroy

    redirect_to(events_path)
  end
end
